package com.zhp.farmerclient.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhp.farmerclient.common.Result;
import com.zhp.farmerclient.entity.Admin;
import com.zhp.farmerclient.mapper.AdminMapper;
import com.zhp.farmerclient.utils.JwtUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class AdminService {

    @Autowired
    public AdminMapper adminMapper;

    @Autowired
    public JwtUtils jwtUtils;

    //注册
    public Result register(Admin admin) {
        // 判断用户名是否已经存在
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("name", admin.getName());
        if (adminMapper.selectCount(wrapper) > 0) {
            // 用户名已存在，注册失败
            return Result.fail(null);
        }
        // 注册成功
        adminMapper.insert(admin);
        return Result.succ();
    }
    //登录
    public Result login(String name, String password, HttpServletResponse response) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        Admin admin = adminMapper.selectOne(queryWrapper);
        Assert.notNull(admin,"账号不存在！");
        if(!admin.getPassword().equals(password)){
            return Result.fail("密码错误！");
        }
//        String jwt = jwtUtils.generateToken(admin.getId());
//        System.out.println(jwt);
//        response.setHeader("Authorization", jwt);
//        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return Result.succ().data("name",name).data("password",password).data("id",admin.getId());
    }
    //查看个人信息
    public Result check(int id){
        Admin admin  = adminMapper.selectById(id);
        return Result.succ(admin,null);
    }
    //修改个人信息
    public Result save(Admin admin) {
        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",admin.getId());
        adminMapper.update(admin,updateWrapper);
        return Result.succ();
    }
}
